//
//  AppDelegate.swift
//  VenusMaster
//
//  Created by qurongxiang on 2018/10/27.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate {
    
    var window: UIWindow?
    var _mapManager: BMKMapManager?
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        //适配12.1BUG
        UITabBar.appearance().isTranslucent = false
        
        IQKeyboardManager.shared.enable = true
        setupBaiDuNav()
        setupPush(launchOptions: launchOptions)
        
        window?.backgroundColor = UIColor.white
        UITabBar.appearance().tintColor = kColorDarkSlateGray
        UIApplication.shared.statusBarStyle = .lightContent
        self.window = UIWindow(frame:UIScreen.main.bounds)
        
        if UserInfo.shareInstance.userModel().id == 0 { //注册 登录 配置
            let registerVC =  LogionViewController()
            self.window?.rootViewController = registerVC
        }else {
          
            UMessage.setAlias(String(UserInfo.shareInstance.userModel().id), type: "ALIAS_TYPE.DIPAI", response: { (result, error) in
                print("友盟：",UserInfo.shareInstance.userModel().id)
            })
            self.window?.rootViewController = MPTabBarController()
        }
        self.window?.makeKeyAndVisible()
        
       
        
        return true
    }
    
    /// 推送
    func setupPush(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        UMConfigure.initWithAppkey("5be67ebab465f590780000c1", channel: "App Store")
        let entity = UMessageRegisterEntity()
        //声音，弹窗，角标 默认就是
        entity.types = Int(UInt8(UMessageAuthorizationOptions.badge.rawValue) | UInt8(UMessageAuthorizationOptions.alert.rawValue) |  UInt8(UMessageAuthorizationOptions.sound.rawValue))
        UNUserNotificationCenter.current().delegate = self
        UMessage.registerForRemoteNotifications(launchOptions: launchOptions, entity: entity) { (error, errorInfo) in
            print("友盟推送",error,errorInfo ?? "成功啦")
        }
    }
    
    /// 认证百度地图 + 定位 + 导航
    func setupBaiDuNav() {
        _mapManager = BMKMapManager()
        let ret = _mapManager?.start("OSwnySBcDOoIOGGklsThRh7t0tGeugbS", generalDelegate: nil)
        if ret == true  {
            print("百度地图OK")
        }
        
        BMKLocationAuth.sharedInstance()?.checkPermision(withKey: "OSwnySBcDOoIOGGklsThRh7t0tGeugbS", authDelegate: nil)
        
        BNCoreServices.getInstance().startAsyn({
            BNCoreServices.getInstance().authorizeNaviAppKey("OSwnySBcDOoIOGGklsThRh7t0tGeugbS") { (suc) in print("百度导航",suc) }
            BNCoreServices.getInstance().authorizeTTSAppId("14672994", apiKey: "OSwnySBcDOoIOGGklsThRh7t0tGeugbS", secretKey: "pp4bzW2Ur04HgQEogzUdovS7GFfj1Yv3", completion: { (suc) in
                print("百度导航TTS",suc)
            })
        }) {}
    }
    
    
    
    ///前台
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        
        if notification.request.trigger is UNPushNotificationTrigger {
            UMessage.setAutoAlert(false)
            UMessage.didReceiveRemoteNotification(userInfo)
        }
        
        //当应用处于前台时提示设置，需要哪个可以设置哪一个
        completionHandler(UNNotificationPresentationOptions(rawValue: UNNotificationPresentationOptions.RawValue(UInt8(UNNotificationPresentationOptions.sound.rawValue) | UInt8(UNNotificationPresentationOptions.badge.rawValue) | UInt8(UNNotificationPresentationOptions.alert.rawValue))))
    }
    
    
    ///后台
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger is UNPushNotificationTrigger {
            UMessage.setAutoAlert(false)
            UMessage.didReceiveRemoteNotification(userInfo)
        }
    }
    
    
    ///获取到了token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let device = NSData(data: deviceToken)
        let deviceId = device.description.replacingOccurrences(of:"<", with:"").replacingOccurrences(of:">", with:"").replacingOccurrences(of:" ", with:"")
        print("我的deviceToken：\(deviceId)")
        
        
    }
    
    ///注册通知失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("tokenerror===",error)
    }
    
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    
}

